import './style.scss'
import config from './config';
import { promises } from './service/image';
import straw from './canvas/straw';
import wall from './canvas/wall';
import water from './canvas/water';
import steel from './canvas/steel';
import tank from './canvas/tank';
import bullet from './canvas/bullet';
import play from './canvas/play';
import boss from './canvas/boss';
import audios from './service/audios';
import { cond } from 'lodash';

const app = document.querySelector<HTMLDivElement>('#app')!;
app.style.width = config.canvas.width + 'px';
app.style.height = config.canvas.hieght + 'px';

// 初始化画布
export default {
  isStart: false,
  state: 9,
  interval: 0,
  boostrap() {
    document.addEventListener('click', () => {
      this.start();
      this.interval = setInterval(() => { 
        tank.modelist.length <= 0 && (this.state = 1);
        (play.modelist.length <= 0 || boss.modelist.length <= 0) && (this.state = 0);
        if (this.state !== 9) {
          this.stop();
        }
      }, 100);
    });
  },
  async start() {
    if (this.isStart) return;
    this.isStart = true;
    app.style.background = 'gray';
    // 开始的音乐
    audios.start();
    // 1、载入图片素材
    await Promise.all(promises);
      // 2、绘制草地canvas
      straw.render();
      wall.render();
      water.render();
      steel.render();
      tank.render();
      play.render();
      boss.render();
      bullet.render();
  },
  stop() {
    console.log('游戏停止');
    clearInterval(this.interval);
    tank.stop();
    bullet.stop();
    // 展示结果文案
    this.text();
  },
  text() {
    let textCanvas: HTMLCanvasElement = document.createElement('canvas');
    textCanvas.width = config.canvas.width;
    textCanvas.height = config.canvas.hieght;
    // 绘制文字
    let ctx = textCanvas.getContext('2d');
    ctx!.fillStyle = 'red';
    ctx!.font = '80px CascadiaMono';
    (<CanvasRenderingContext2D>ctx).textAlign = 'center';
    ctx!.textBaseline = 'middle';
    ctx?.fillText(this.state === 1 ? '恭喜获胜' : '遗憾失败', config.canvas.width / 2, config.canvas.hieght / 2);
    app.appendChild(textCanvas);
  }
}
